const fs = require('fs');
const path = require('path');
const { parentPort } = require('worker_threads');
const db = require('../models');
const OpLogs = db.models.opLogs;
const logger = require('./_logger')

const activeLogFilePath = path.resolve(process.cwd(), 'logs/operation_logs_active.log');
const pendingLogFilePath = path.resolve(process.cwd(), 'logs/operation_logs_pending.log');

parentPort.on('message', async () => {
    try {
        // 先检查 日志文件是否存在，不存在则结束
        if (!fs.existsSync(activeLogFilePath)) return;
        // 将活跃日志文件重命名为待处理文件
        fs.renameSync(activeLogFilePath, pendingLogFilePath);

        // 读取待处理文件中的日志
        const logList = fs.readFileSync(pendingLogFilePath, 'utf-8')
            .split('\n')
            .filter(Boolean)
            .map(line => JSON.parse(line));

        // 批量插入数据库
        if (logList.length) {
            await OpLogs.bulkCreate(logList)
            // 删除待处理文件
            fs.unlinkSync(pendingLogFilePath)
        }
    } catch (error) {
        logger.errLog(`记录操作日志【子进程】：${error}`);
    }
})